package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wmUser.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.UserMapper;
import com.heima.user.service.UserService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, ApUserRealname> implements UserService {
    /**
     * 模糊分页查询
     */
    @Override
    public ResponseResult findUserByPage(UserDto userDto) {
        //判断数据是否合法
        if (userDto == null) {
            CustomException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        userDto.checkParam();
        //执行查询操作
        Page<ApUserRealname> page = new Page<>(userDto.getPage(), userDto.getSize());
        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(userDto.getStatus() != null, ApUserRealname::getStatus, userDto.getStatus());
        wrapper.orderByDesc(ApUserRealname::getCreatedTime);
        IPage<ApUserRealname> resultPage = page(page, wrapper);
        List<ApUserRealname> records = resultPage.getRecords();
        return new PageResponseResult(userDto.getPage(), userDto.getSize(), resultPage.getTotal(), resultPage.getRecords());
    }

    @Autowired
    private ApUserMapper apUserMapper;
    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private ArticleFeign articleFeign;


    /**
     * 自媒体用户审核
     */
    @GlobalTransactional//分布式事务支持
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(UserDto dto, Short status) {
        //判断数据是否合法
        if (dto == null || dto.getId() == null) {
            CustomException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断当前待审核用户是否存在
        ApUserRealname userRealNameById = getById(dto.getId());
        if (userRealNameById == null) {
            CustomException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断当前用户是否为待审核状态
        if (userRealNameById.getStatus() != 1) {
            CustomException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "审核状态错误");
        }
        //查询app端是否有关联的用户
        ApUser apUser = apUserMapper.selectById(userRealNameById.getId());
        if (apUser == null) {
            CustomException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "当前用户不存在");
        }
        //设置当前待审核状态的基本信息 修改时间 审核状态码
        userRealNameById.setStatus(status);
        userRealNameById.setUpdatedTime(new Date());
        String failMsg = dto.getMsg();
        if (StringUtils.isNotBlank(failMsg)) {
            userRealNameById.setReason(failMsg);
        }
        updateById(userRealNameById);
        //如果审核驳回则直接返回审核结果
        if (status == 2) {
            return ResponseResult.okResult();
        }
        //如果审核通过则创建自媒体账户和作者信息
        WmUser memdia = createWemedia(apUser);
        createAuthor(apUser, memdia);
        return ResponseResult.okResult();
    }

    /**
     * 创建自媒体用户
     */
    @Transactional(rollbackFor = Exception.class)
    public WmUser createWemedia(ApUser apUser) {
        //使用feign远程调用自媒体微服务判断当前用户是否已经存在
        //判断远程调用是否成功
        ResponseResult<WmUser> res = wemediaFeign.findWmUserByName(apUser.getName());
        if (res.getCode().intValue() != 0) {//ResponseResult.okResult()的状态码为0，表成功
            CustomException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, res.getErrorMessage());
        }
        //判断用户是否已经存在
        WmUser data = res.getData();
        if (data != null) {
            CustomException.cust(AppHttpCodeEnum.DATA_EXIST, "当前自媒体用户已经存在");
        }
        //新建自媒体用户 封装信息
        WmUser wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId()); // apuserid
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
        //使用feign远程调用自媒体微服务模块实现创建自媒体用户
        ResponseResult<WmUser> responseResult = wemediaFeign.addWmUser(wmUser);
        if (responseResult.getCode().intValue() != 0) {
            CustomException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, responseResult.getErrorMessage());
        }
        //返回当前自媒体用户，以备创建作者信息的时候使用
        return responseResult.getData();

    }

    /**
     * 创建作者信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void createAuthor(ApUser apUser, WmUser wmUser) {
        //使用feign远程调用文章模块，判断是否已经存在该作者信息
        ResponseResult<ApAuthor> res = articleFeign.findAuthorByUserId(apUser.getId());
        if (res.getCode().intValue() != 0) {
            CustomException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, res.getErrorMessage());
        }
        ApAuthor data = res.getData();
        if (data != null) {
            CustomException.cust(AppHttpCodeEnum.DATA_EXIST, "当前作者信息已经存在");
        }
        //新建作者对象 封装信息
        ApAuthor author = new ApAuthor();
        author.setName(apUser.getName());
        author.setType(2);
        author.setUserId(apUser.getId());
        author.setCreatedTime(new Date());
        author.setWmUserId(wmUser.getId());
        //远程调用article模块 实现添加作者的操作
        System.out.println("11111111111111111111111111111");
        ResponseResult<ApAuthor> response = articleFeign.addAuthor(author);
        if (response.getCode().intValue() != 0) {
            CustomException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, response.getErrorMessage());
        }
    }
}
